import logging
import os, pdb
import time
from conf.sysConfig import config
from django.http import JsonResponse
from software.utils import fileStore
from software.models import Software, SoftwareType, SoftwareVersion, SoftwareData
from storehouse.models import Storehouse
from user import dataCheck as da
from user.dataCheck import DataCheck
from user.models import Company, FileStore

datacheck = DataCheck()
tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")


# 首先握手 检查文件
def check_file(request, *args, **kwargs):
    recv_data = request.data  # 得到前端传送的数据
    file_list = []
    for root, dirs, files in os.walk(tmpDir):
        file_list.append(files)  # 当前路径下所有非目录子文件
    data = {
        'code': 0,
        'msg': 'success',
    }
    logger_request.info(data)
    return JsonResponse(data)


# app.route('/file/upload', methods=['POST'])
def upload_part(request, *args, **kwargs):  # 接收前端上传的一个分片
    task = request.form.get('task_id')  # 获取文件的唯一标识符
    chunk = request.form.get('chunk', 0)  # 获取该分片在所有分片中的序号
    filename = '%s%s' % (task, chunk)  # 构造该分片的唯一标识符
    upload_file = request.files['file']
    upload_file.save(tmpDir + '/%s' % filename)  # 保存分片到本地
    data = {
        'code': 0,
        'msg': 'success',
    }
    logger_request.info(data)
    return JsonResponse(data)


# app.route('/file/merge', methods=['GET'])
def upload_success(request, *args, **kwargs):  # 按序读出分片内容，并写入新文件
    target_filename = request.args.get('filename')  # 获取上传文件的文件名
    task = request.args.get('task_id')  # 获取文件的唯一标识符
    chunk = 0  # 分片序号
    with open(tmpDir + '/%s' % target_filename, 'wb') as target_file:  # 创建新文件
        while True:
            try:
                filename = tmpDir + '/%s%d' % (task, chunk)
                source_file = open(filename, 'rb')  # 按序打开每个分片
                target_file.write(source_file.read())  # 读取分片内容写入新文件
                source_file.close()
            except(IOError):
                break
            chunk += 1
    chunk = 0  # 分片序号
    while True:
        try:
            filename = tmpDir + '/%s%d' % (task, chunk)
            os.remove(filename)  # 删除该分片，节约空间
        except(IOError):
            break
        chunk += 1
    data = {
        'code': 0,
        'msg': 'success',
    }
    logger_request.info(data)
    return JsonResponse(data)
